package uk.co.q3c.deplan.server.unit.service;

import org.apache.log4j.Logger;

import uk.co.q3c.deplan.client.domain.resource.IndividualResource;
import uk.co.q3c.deplan.client.domain.resource.PersistenceReferenceException;
import uk.co.q3c.deplan.client.domain.resource.ResourceGroup;
import uk.co.q3c.deplan.client.domain.resource.ResourcePool;
import uk.co.q3c.deplan.client.service.ServiceFactory;
import uk.co.q3c.deplan.server.util.XMLImport;

import com.google.appengine.repackaged.com.google.common.collect.Lists;

public class ImportAction {
	transient protected final Logger logger = Logger.getLogger(getClass().getName());
	private boolean overwrite;
	private ServiceFactory connection;

	public ImportAction() {
	}

	public void run() throws PersistenceReferenceException {
		logger.info("Importing ...");

		XMLImport xi = setupImporter();
		try {
			xi.execute(connection);
			logger.info("import complete");
			// Server.setCurrentDb(db);
			if (overwrite) {
				// Server.delete(db);
			}
			// testdao.getDbc().open();
			xi.persist();
			logger.info("Import stored in " + connection.taskService()
					.toString());
			int projectCount = connection.taskService()
					.countProjects();
			logger.info("Total projects confirmed in database " + projectCount);
			// Server.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private XMLImport setupImporter() throws PersistenceReferenceException {
		XMLImport xi = new XMLImport();
		ResourcePool resourcePool = new ResourcePool(connection);
		String[] names = new String[] { "dsowerby", "gryder", "mpaine", "svanage", "ahare", "ldi-niro", "rvafadari", "jwashington" };
		IndividualResource[] resources = new IndividualResource[names.length];
		for (int i = 0; i < names.length; i++) {
			resources[i] = new IndividualResource(connection);
			resources[i].setName(names[i]);
			resourcePool.addResource(resources[i]);
		}
		ResourceGroup group = resourcePool.groupContainingOnly(Lists.newArrayList(resources));
		group.setName("SysDev");
		// resourcePool.addResource(group);
		resourcePool.setDefaultResourceName(group.getName());

		xi.setSource("/home/dave/develop/workspace/dePlanTest/src/Master Plan.xml");
		xi.setResourcePool(resourcePool);
		xi.setDefaultResourceName("SysDev");
		return xi;
	}

	public void setImportDb(ServiceFactory connection, boolean overwrite) {
		this.connection = connection;
		this.overwrite = overwrite;

	}
}
